package com.cloud.xtools.common.validator;

import com.cloud.xtools.common.validator.annotation.SizeIfExist;
import jakarta.validation.ConstraintValidator;
import jakarta.validation.ConstraintValidatorContext;

/**
 * @author Daixinguo
 */
public class SizeIfExistValidator implements ConstraintValidator<SizeIfExist,Object> {

    private int min;
    private int max;

    @Override
    public void initialize(SizeIfExist constraintAnnotation) {
        ConstraintValidator.super.initialize(constraintAnnotation);
        this.min = constraintAnnotation.min();
        this.max = constraintAnnotation.max();
    }

    @Override
    public boolean isValid(Object value, ConstraintValidatorContext constraintValidatorContext) {
        final String strValue = (String) value;
        if (strValue == null || strValue.isEmpty()) {
            // 如果密码为空，则不进行长度验证
            return true;
        }
        return strValue.length() >= min && strValue.length() <= max;
    }
}
